﻿using System;
using System.Collections.Generic;
using System.Linq;
using Ymatou.API.Common;
using Ymatou.CommonService;
using Ymatou.Evaluate.Data.Query;
using Ymatou.Evaluate.Entity;
using Ymatou.ProductQuery.BuyerModel.Request.ListRequest;
using Ymatou.ServiceCenter;
using Ymatou.User.Dto;

namespace Ymatou.Evaluate.Service
{
    public class QueryService
    {
        [Serializable]
        class ResponseBaseModel<T>
        {
            public int ResponseCode { get; set; }
            public bool Success { get; set; }
            public T Result { get; set; }
        }

        /// <summary>
        /// 获取评论总数
        /// </summary>
        /// <param name="sellerid"></param>
        /// <param name="score"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public EvaluateCountEntity GetEvaluateCount(int? sellerid,decimal score,DateTime?beginTime,DateTime? endTime)
        {
            var entity = EvaluateQueryData.GetEvaluateCount(sellerid, score, beginTime, endTime);
            if (entity != null)
            {
                entity.Score = score;
                return entity;
            }
            return null;
        }

        /// <summary>
        /// 获取评论列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="totalCount"></param>
        /// <param name="imgs"></param>
        /// <param name="replies"></param>
        /// <returns></returns>
        public List<EvaluateProduct> GetEvaluateProductList(BaseQueryCondition condition,out int totalCount, out List<EvaluateImgs> imgs,out List<EvaluateReply> replies)
        {
            return EvaluateQueryData.GetEvaluateProductList(condition, out totalCount, out imgs, out replies);
        }

        /// <summary>
        /// 批量获取订单评价
        /// </summary>
        /// <param name="orderIds"></param>
        /// <returns></returns>
        public IEnumerable<EvaluateOrder> GetEvaluateOrderByOrderIds(List<int> orderIds)
        {
            return EvaluateQueryData.GetEvaluateOrderByOrderIds(orderIds);
        }

        /// <summary>
        /// 批量查询用户LoginId
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public Dictionary<int, string> GetUserLoginIdByUserIds(List<int> userIds)
        {
            if (userIds == null || !userIds.Any())
            {
                return new Dictionary<int, string>();
            }
            var dic = userIds.Distinct().ToDictionary(userId => userId, userId => string.Empty);

            var request = new BatchUserRequestDto
            {
                UserIdList = userIds.ToArray()
            };
            try
            {
                var data = ServiceClient.Execute(request);
                var response = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseBaseModel<List<BatchUserReponseDto>>>(data);
                if (response != null && response.Success && response.Result != null)
                {
                    
                    response.Result.ForEach(u =>
                    {
                        if (dic.ContainsKey(u.UserId))
                        {
                            dic[u.UserId]=u.LoginId;
                        }
                    });
                    return dic;
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Info(string.Format("批量查询用户信息发生异常request：{0}",
                    Newtonsoft.Json.JsonConvert.SerializeObject(request)));
                ApplicationLog.Error("批量查询用户信息发生异常", ex);
            }
            return dic;
        }

        /// <summary>
        /// 批量查询商品名称和图片
        /// </summary>
        /// <param name="productIds"></param>
        /// <returns></returns>
        public IEnumerable<Tuple<string, string, string>> GetProductInfoByProductIds(List<string> productIds)
        {
            productIds = productIds.Distinct().ToList();

            var request = new GetProductDetailListByTradeIsolationRequest
            {
                ProductIdList = productIds,
                AppId = "evaluate.iapi.ymatou.com"
            };

            try
            {
                var response =
                    ServiceClient
                        .Execute
                        <GetProductDetailListByTradeIsolationRequest,
                            BaseResponseModel
                                <
                                    ProductQuery.BuyerModel.Response.ListResponse.
                                        GetProductDetailListByProductIdListResponse>>(request);
                if (response == null) return null;
                if (response.RetCode == 200 && response.RetData != null && response.RetData.ProductList != null &&
                    response.RetData.ProductList.Any())
                {
                    var retList = response.RetData.ProductList.Select(
                        p =>
                            new Tuple<string, string, string>(p.ProductId, p.Title,
                                p.PicList.FirstOrDefault() ?? string.Empty)).ToList();
                    var exceptProdIds = response.RetData.ProductList.Select(p => p.ProductId).Except(productIds);
                    if (exceptProdIds.Any())
                    {
                        retList.AddRange(GetHisProductInfoByProductIds(exceptProdIds.ToList()));
                    }
                    return retList;
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Info(string.Format("批量查询商品信息发生异常request：{0}",
                    Newtonsoft.Json.JsonConvert.SerializeObject(request)));
                ApplicationLog.Error("批量查询商品信息发生异常", ex);
            }
            return new List<Tuple<string, string, string>>();
        }

        /// <summary>
        /// 批量查询商品名称和图片
        /// </summary>
        /// <param name="productIds"></param>
        /// <returns></returns>
        private IEnumerable<Tuple<string, string, string>> GetHisProductInfoByProductIds(List<string> productIds)
        {
            productIds = productIds.Distinct().ToList();

            var request = new GetProductListByHistoryProductIdListRequest
            {
                ProductIdList = productIds,
                AppId = "evaluate.iapi.ymatou.com"
            };

            try
            {
                var response =
                    ServiceClient
                        .Execute
                        <GetProductListByHistoryProductIdListRequest,
                            BaseResponseModel
                                <
                                    ProductQuery.BuyerModel.Response.ListResponse.
                                        GetProductListByHistoryProductIdListResponse>>(request);
                if (response == null) return null;
                if (response.RetCode == 200 && response.RetData != null && response.RetData.ProductList != null &&
                    response.RetData.ProductList.Any())
                {
                    return
                        response.RetData.ProductList.Select(
                            p =>
                                new Tuple<string, string, string>(p.ProductId, p.Title, p.MainPic ?? string.Empty)).ToList();
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Info(string.Format("批量查询历史商品信息发生异常request：{0}",
                    Newtonsoft.Json.JsonConvert.SerializeObject(request)));
                ApplicationLog.Error("批量查询历史商品信息发生异常", ex);
            }
            return new List<Tuple<string, string, string>>();
        }
    }
}
